package com.memory.monitor.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.memory.monitor.common.DeleteRequest;
import com.memory.monitor.common.ErrorCode;
import com.memory.monitor.constant.ExcelConstant;
import com.memory.monitor.exception.BusinessException;
import com.memory.monitor.exception.ThrowUtils;
import com.memory.monitor.job.AreaExcelListener;
import com.memory.monitor.job.DistributeExcelListener;
import com.memory.monitor.job.InstitutionExcelListener;
import com.memory.monitor.mapper.InstitutionMapper;
import com.memory.monitor.model.dto.area.AreaQuerryRequest;
import com.memory.monitor.model.dto.area.AreaUpdateRequest;
import com.memory.monitor.model.dto.institution.InstitutionAddRequest;
import com.memory.monitor.model.dto.institution.InstitutionQueryRequest;
import com.memory.monitor.model.dto.institution.InstitutionUpdateRequest;
import com.memory.monitor.model.entity.Area;
import com.memory.monitor.model.entity.Distribute;
import com.memory.monitor.model.entity.Institution;
import com.memory.monitor.model.entity.User;
import com.memory.monitor.model.vo.DistributeVO;
import com.memory.monitor.model.vo.InstitutionVO;
import com.memory.monitor.service.AreaService;
import com.memory.monitor.service.InstitutionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static com.memory.monitor.constant.ExcelConstant.*;

/**
* @author 21731
* @description 针对表【institution(机构管理)】的数据库操作Service实现
* @createDate 2024-09-02 09:59:49
*/
@Service
public class InstitutionServiceImpl extends ServiceImpl<InstitutionMapper, Institution>
    implements InstitutionService {

    /**
     * 封装InstitutionVO对象
     * @param institution
     * @return
     */

    @Override
    public InstitutionVO getinstitutionVO(Institution institution) {
        if (institution == null) {
            return null;
        }
        InstitutionVO institutionVO = new InstitutionVO();
        BeanUtils.copyProperties(institution, institutionVO);
        return institutionVO;
    }

    /**
     * 封装InstitutionVO对象
     * @param institutionList
     * @return
     */
    @Override
    public List<InstitutionVO> getdistributeVO(List<Institution> institutionList) {
        if (CollectionUtils.isEmpty(institutionList)) {
            return new ArrayList<>();
        }
        return institutionList.stream().map(this::getinstitutionVO).collect(Collectors.toList());
    }
    /**
     * 查询机构信息
     * @param institutionQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Institution> getQueryWrapper(InstitutionQueryRequest institutionQueryRequest) {
        if (institutionQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = institutionQueryRequest.getId();

        String institutionName = institutionQueryRequest.getInstitutionName();
        String addressId = institutionQueryRequest.getAddressId();
        String type = institutionQueryRequest.getType();
        String area = institutionQueryRequest.getArea();
        Integer status = institutionQueryRequest.getStatus();

        QueryWrapper<Institution> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(id != null, "id", id);
        queryWrapper.like(StringUtils.isNotBlank(institutionName), "institution_name", institutionName);
        queryWrapper.eq(StringUtils.isNotBlank(addressId), "address_id", addressId);
        queryWrapper.eq(StringUtils.isNotBlank(type), "type", type);
        queryWrapper.eq(StringUtils.isNotBlank(area), "area", area);
        queryWrapper.eq(status!=null, "status", status);
        return queryWrapper;
    }


    /**
     * 增加机构信息
     * @param institutionAddRequest
     * @return
     */
    @Override
    public Long addInstitution(InstitutionAddRequest institutionAddRequest) {
        if (institutionAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Institution institution = new Institution();

        BeanUtils.copyProperties(institutionAddRequest, institution);
        boolean result = this.save(institution);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return institution.getId();
    }

    /**
     * 修改机构信息
     * @param institutionUpdateRequest
     * @return
     */
    @Override
    public Boolean updateInstitution(InstitutionUpdateRequest institutionUpdateRequest) {
        if (institutionUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Institution institution = new Institution();

        BeanUtils.copyProperties(institutionUpdateRequest,institution);
        boolean result = this.updateById(institution);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return result;
    }


    /**
     * 删除机构信息
     * @param deleteRequest
     * @return
     */
    @Override
    public Boolean deleteInstitution(DeleteRequest deleteRequest) {
        if (deleteRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = this.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(result, ErrorCode.OPERATION_ERROR);
        return result;
    }

    @Override
    public List<InstitutionVO> listInstitutionByPage() {
        return getdistributeVO(this.list());
    }

    @Override
    public Boolean readExcel(MultipartFile multipartFile) {
        // 1.转换文件为字节流
        InputStream inputStream;
        try {
            inputStream = multipartFile.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 2.执行文件处理逻辑
        EasyExcel.read(inputStream, Institution.class, new InstitutionExcelListener()).sheet().doRead();
        // 3.入库
        boolean saveBatch = this.saveBatch(InstitutionExcelListener.CACHED_DATA_LIST);

        ThrowUtils.throwIf(!saveBatch, ErrorCode.PARAMS_ERROR);
        return true;
    }

    @Override
    public Boolean writeExcel(String path) {
        // 1.定义文件路径
        String fullPath = DOWNLOAD_PATH + AREA_TABLE_NAME;
        // 2.检查文件是否存在
        ExcelConstant.isExist(fullPath);
        // 3.根据路径导出
        List<InstitutionVO> institutionList = this.listInstitutionByPage();
        EasyExcel.write(fullPath, User.class).sheet(AREA_SHEET_NAME).doWrite(institutionList);

        return true;
    }
}




